package cn.jhc.teachingquality.net.practice;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.bean.PracticeLog;
import cn.jhc.teachingquality.net.TeachingQualityRequest;

import static cn.jhc.teachingquality.Global.LOG_TAG;
import static cn.jhc.teachingquality.Global.URL_PREFIX;

/**
 * Created by luyanfei on 16-3-9.
 */
public class ListPracticesRequest extends TeachingQualityRequest<List<PracticeLog>> {
    private static final String LIST_PRACTICE_URL = URL_PREFIX + "/dgSxrzAction!list.shtml";

    public ListPracticesRequest(Response.Listener<List<PracticeLog>> listener) {
        super(Method.POST, LIST_PRACTICE_URL, listener);
    }


    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> map = new HashMap<>();
        //同时显示400条记录
        map.put("page.pageSize", Global.PAGE_SIZE);
        return map;
    }

    @Override
    protected List<PracticeLog> handleResponse(Document document) {
        List<PracticeLog> list = new ArrayList<>();
        Elements totalLogs = document.select("#listBody tr");
        for (Element e : totalLogs) {
            String hiddenId;
            String student;
            int weekSeq;
            String title;
            //过滤掉无法获得idKeys的元素
            try {
                hiddenId = e.getElementsByAttributeValue("name", "idKeys").first().val().trim();
                student = e.getElementsByAttributeValue("name", "jcXsxx.xsXm").first().text().trim();
                weekSeq = Integer.valueOf(e.getElementsByAttributeValue("name", "zc").first().text().trim());
                title = e.getElementsByAttributeValue("name", "bt").first().text().trim();
            } catch (NullPointerException npe) {
                Log.w(LOG_TAG, "Skip one tr element in Practice Log lists.");
                continue;
            }
            PracticeLog practiceLog = new PracticeLog(title, student, weekSeq, hiddenId);
            list.add(practiceLog);
         }
        Log.d(LOG_TAG, "Fetched " + list.size() + " lines of practice log entry.");
        return list;
    }

}
